package io.renren.modules.sys.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import io.renren.common.annotation.SysLog;
import io.renren.common.utils.Constant;
import io.renren.common.utils.R;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.form.LoginForm;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.service.SysUserTokenService;
import opennlp.tools.parser.Cons;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 登录相关
 * 
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年11月10日 下午1:15:31
 */
@RestController
public class SysLoginController extends AbstractController {
	@Autowired
	private Producer producer;
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;

	/**
	 * 验证码
	 */
	@RequestMapping("captcha.jpg")
	public void captcha(HttpServletResponse response)throws ServletException, IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//生成文字验证码
		String text = producer.createText();
		//生成图片验证码
		BufferedImage image = producer.createImage(text);
		//保存到shiro session
		ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY, text);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@RequestMapping(value = "/sys/login", method = RequestMethod.POST)
	public Map<String, Object> login(@RequestBody LoginForm form)throws IOException {
		//本项目已实现，前后端完全分离，但页面还是跟项目放在一起了，所以还是会依赖session
		//如果想把页面单独放到nginx里，实现前后端完全分离，则需要把验证码注释掉(因为不再依赖session了)
		String kaptcha = ShiroUtils.getKaptcha(Constants.KAPTCHA_SESSION_KEY);
		if(!form.getCaptcha().equalsIgnoreCase(kaptcha)){
			return R.error("验证码不正确");
		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}

		//生成token，并保存到数据库
		R r = sysUserTokenService.createToken(user.getUserId());
		return r;
	}

	/**
	 * 获取登陆用token
	 * @author xuwangcheng
	 * @date 2019/9/29 16:57
	 * @param token token
	 * @param username username
	 * @param userId userId
	 * @return {@link R}
	 */
	@RequestMapping("/sso/getSSoLoginToken")
	public R getSSoLoginToken (@RequestParam String token, @RequestParam String username, @RequestParam String userId) {
		if (StringUtils.isAnyBlank(token, userId) || !StringUtils.isNumeric(userId)) {
			return R.error("请求参数不正确");
		}

		//验证token是否正确
		if (!Constant.API_TOKEN.equalsIgnoreCase(token)) {
			return R.error("token不正确");
		}

		//验证用户是否存在，如果不存在则添加
		SysUserEntity sysUserEntity = sysUserService.queryObject(Long.valueOf(userId));
		if (sysUserEntity == null) {
			sysUserEntity = new SysUserEntity();
			sysUserEntity.setCheckRole(false);
			sysUserEntity.setUsername(username);
			sysUserEntity.setPassword("11111111");
			sysUserEntity.setEmail("");
			sysUserEntity.setMobile("");
			sysUserEntity.setStatus(1);
			sysUserEntity.setCreateUserId(Long.valueOf(Constant.SUPER_ADMIN));
			sysUserEntity.setUserId(Long.valueOf(userId));

			List<Long> roleList = new ArrayList<>();
			roleList.add(Long.valueOf(Constant.DEFAULT_PTS_ROLE_ID));
			sysUserEntity.setRoleIdList(roleList);

			sysUserService.save(sysUserEntity);
		}

		//如果用户名变更了，则修改信息
		if (!username.equals(sysUserEntity.getUsername())) {
			sysUserEntity.setUsername(username);

			sysUserService.update(sysUserEntity);
		}

		//创建登陆token
		R r = sysUserTokenService.createToken(sysUserEntity.getUserId());

		return r;
	}


	/**
	 * 退出
	 */
	@RequestMapping(value = "/sys/logout", method = RequestMethod.POST)
	public R logout() {
		sysUserTokenService.logout(getUserId());
		return R.ok();
	}
	
}
